<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import {
  getAlertPeopleMsgListApi,
  deleteAlertPeopleMsgApi,
  batchDeleteAlertPeopleMsgApi,
  AlertPeopleMsgModel
} from "@/api/alerts/alertPeopleMsg";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";
import { useLogic } from "@/views/system/user/logic/logic";

defineOptions({
  name: "people-msg"
});

const i18n = useI18n();
const { t } = i18n;
const pageSizeOps = ref(pageSizeOptions);

const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () => {
  await getDeptTree()
})

const searchDefault = {
  alertLogId: undefined,
  peopleId: undefined,
  noticeType: undefined,
  status: undefined,
  timeRange: [],
  deptId: undefined,
  pageSize: 10,
  page: 1,
}
// 搜索参数
const searchParams = ref(Object.assign({},searchDefault));

// 搜索字段配置
const searchFields = ref([
  {
    prop: "alertLogId",
    name: t("alerts.alertPeopleMsgPage.search.alertLogId"),
    type: "input",
    placeholder: "",
  },
  {
    prop: "peopleId",
    name: t("alerts.alertPeopleMsgPage.search.peopleId"),
    type: "input",
    placeholder: "",
  },
  {
    prop: "noticeType",
    name: t("alerts.alertPeopleMsgPage.search.noticeType"),
    type: "select",
    formOptions: [
      { val: 'sms', label: t("alerts.alertPeopleMsgPage.noticeType.sms") },
      { val: 'email', label: t("alerts.alertPeopleMsgPage.noticeType.email") }
    ]
  },
  {
    prop: "status",
    name: t("alerts.alertPeopleMsgPage.search.status"),
    type: "select",
    formOptions: [
      { val: 1, label: t("alerts.alertPeopleMsgPage.status.ok") },
      { val: -1, label: t("alerts.alertPeopleMsgPage.status.failed") },
      { val: 0, label: t("alerts.alertPeopleMsgPage.status.processing") }
    ]
  },
  { prop: 'timeRange', name: t("buttons.timeRange"), type: 'datetimeRange', clearable: true, isHidden: false, },
  { prop: 'deptId', name: t("alerts.alertPeopleMsgPage.table.deptId"), type: 'cascader', cascaderOptions: deptTreeList, ops: { valueField: 'id', labelField: 'name', emitPath: false, checkStrictly: true } },
]);

// 表格数据
const tableData = ref<AlertPeopleMsgModel[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref<AlertPeopleMsgModel[]>([]);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = { ...searchParams.value };
    const response = await getAlertPeopleMsgListApi(params);
    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || t('alerts.alertPeopleMsgPage.getFailed'));
    }
  } catch (error) {
    total.value = 0;
    tableData.value = [];
    ElMessage.error(t('alerts.alertPeopleMsgPage.getFailed'));
    console.error("Failed to load alert people message list:", error);
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

// 搜索处理
const handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
};

const handleSearch = async (e: any) => {
  searchParams.value.page = 1;
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await loadData();
};

const handleReset = (e: any) => {
  searchParams.value = Object.assign({}, searchDefault)
};

// 刷新列表
const refreshList = () => {
  loadData();
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t('alerts.alertPeopleMsgPage.deleteConfirm'),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteAlertPeopleMsgApi(id);
    if (response.code === 0) {
      ElMessage.success(t('alerts.alertPeopleMsgPage.deleteSuccess'));
      refreshList();
    } else {
      ElMessage.error(response.msg || t('alerts.alertPeopleMsgPage.deleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.alertPeopleMsgPage.deleteFailed'));
    }
  }
};

// 批量删除
const handleSelectionChange = (rows: AlertPeopleMsgModel[]) => {
  selectedRows.value = rows;
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('alerts.alertPeopleMsgPage.selectRecordFirst'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      t('alerts.alertPeopleMsgPage.batchDeleteConfirm', { count: selectedRows.value.length }),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const ids = selectedRows.value.map(row => row.id);
    const response = await batchDeleteAlertPeopleMsgApi(ids);
    
    if (response.code === 0) {
      ElMessage.success(t('alerts.alertPeopleMsgPage.batchDeleteSuccess'));
      await loadData();
      selectedRows.value = [];
    } else {
      ElMessage.error(response.msg || t('alerts.alertPeopleMsgPage.batchDeleteFailed'));
    }
  } catch (error: any) {
    if (error.name !== 'cancel') {
      ElMessage.error(t('alerts.alertPeopleMsgPage.batchDeleteFailed'));
    }
  }
};

// 格式化状态显示
const formatStatus = (status: number) => {
  switch (status) {
    case 1:
      return t('alerts.alertPeopleMsgPage.status.ok');
    case -1:
      return t('alerts.alertPeopleMsgPage.status.failed');
    case 0:
      return t('alerts.alertPeopleMsgPage.status.processing');
    default:
      return status.toString();
  }
};

// 格式化通知类型
const formatNoticeType = (noticeType: string) => {
  return noticeType === 'sms' ? t('alerts.alertPeopleMsgPage.noticeType.sms') : 
         noticeType === 'email' ? t('alerts.alertPeopleMsgPage.noticeType.email') : noticeType;
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="search-area">
        <Searchbox
          :fields="searchFields"
          :initialValues="searchParams"
          :maxVisibleFields="2"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>
    <div class="button-area">
      <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        {{ t('buttons.batchDelete') }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" :label="t('alerts.alertPeopleMsgPage.table.id')" width="80" />
      <el-table-column prop="alertLogId" :label="t('alerts.alertPeopleMsgPage.table.alertLogId')" width="120" />
      <el-table-column prop="peopleId" :label="t('alerts.alertPeopleMsgPage.table.peopleId')" width="120" />
      <el-table-column prop="noticeType" :label="t('alerts.alertPeopleMsgPage.table.noticeType')" width="100">
        <template #default="{ row }">
          {{ formatNoticeType(row.noticeType) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="t('alerts.alertPeopleMsgPage.table.status')" width="100">
        <template #default="{ row }">
          {{ formatStatus(row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="statusMsg" :label="t('alerts.alertPeopleMsgPage.table.statusMsg')" min-width="150" />
      <el-table-column prop="createdAt" :label="t('alerts.alertPeopleMsgPage.table.createdAt')" width="180" />
      <el-table-column prop="updatedAt" :label="t('alerts.alertPeopleMsgPage.table.updatedAt')" width="180" />
      <el-table-column prop="deptId" :label="t('alerts.alertPeopleMsgPage.table.deptId')" width="100" />
      <el-table-column :label="t('alerts.alertPeopleMsgPage.table.operation')" width="100">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.id)"
          >
            {{ t('buttons.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />
  </el-card>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.button-area {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.search-area {
  margin-bottom: 16px;
}
</style>
